﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PickingGuide.Handle
{
    public class TcpServer
    {
        Socket socketServer;
        Encoding encoding = Encoding.UTF8;
        ConcurrentBag<Socket> socketkints = new ConcurrentBag<Socket>();
        public Action<string> ReceiveEvent;

        public void BroadcastMessageToAllClients(string mesg)
        {
            // 将要发送的消息转换为字节数组
            byte[] data = Encoding.UTF8.GetBytes(mesg);

            ConcurrentBag<Socket> sockets = new ConcurrentBag<Socket>();

            // 遍历集合并移除指定元素
            while (!socketkints.IsEmpty && socketkints.TryTake(out var item))
            {
                try
                {
                    // 获取远程端点的IP地址
                    EndPoint remoteEndPoint = item.RemoteEndPoint;
                    if (remoteEndPoint != null)
                    {
                        IPAddress remoteIP = ((IPEndPoint)remoteEndPoint).Address;
                        //LogObj.Debug(DateTime.Now + "TCP发送信息TO: " + remoteIP.ToString());
                    }
                    item.Send(data);
                    sockets.Add(item);
                }
                catch (Exception ex)
                {
                    //LogObj.Error("TCP发送信息异常: " + ex.ToString());
                    //AppendText($"发送异常{ex.Message}", MessageType.Error);
                }
            }
            socketkints = sockets;
        }

        public void StartService(string ip, int port)
        {
            //tcp :协议端
            //实例化一个Tcp协议的socket对象
            socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //给服务器绑定地址与端口
            IPAddress ipaddress = IPAddress.Parse(ip);
            IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, port);
            //把ip与端口绑定在Socket里面
            socketServer.Bind(iPEndPoint);
            //侦听
            socketServer.Listen(100);
            //AppendText("tcp启动", MessageType.Info);
            Task.Run(() =>
            {
                while (true)//循环等待客户端连接
                {
                    //会等待客户端的连接,会卡在这里,不往下运行,直到有下一个宽带连接才会继续往下运行
                    //当有客户端连接的时候,会返回客户端连接的对象
                    Socket socketkint = socketServer.Accept();
                    socketkints.Add(socketkint);
                    byte[] byteff = encoding.GetBytes("200");
                    socketkint.Send(byteff);
                    // 获取远程端点的IP地址
                    EndPoint remoteEndPoint = socketkint.RemoteEndPoint;
                    if (remoteEndPoint != null)
                    {
                        IPAddress remoteIP = ((IPEndPoint)remoteEndPoint).Address;
                        //LogObj.Info("一个客户端建立连接: " + remoteIP.ToString());
                    }                    //AppendText("一个客户端建立连接", MessageType.Info);
                    Task.Run(() =>
                    {
                        try
                        {
                            while (true)//循环接收数据
                            {
                                //接受数据
                                byte[] buffer = new byte[1024];
                                //返回接收到的数据大小,接收数据也会卡住,只有接收到数据的时候才会继续往下进行
                                int longth = socketkint.Receive(buffer);
                                if (longth == 0)
                                {
                                    //AppendText("一个客户端断开连接", MessageType.Info);
                                    return;
                                }
                                //把字符转成字符串
                                string str = encoding.GetString(buffer, 0, longth);
                                ReceiveEvent?.BeginInvoke(str,null,null);                            }
                        }
                        catch (Exception ex)
                        {
                            //AppendText("出现异常", MessageType.Error);
                            return;
                        }
                        finally
                        {
                            socketkint.Close();
                        }
                    });
                }
            });
        }
    }
}
